import * as postsService from '../services/posts';

export default {
    namespace: 'posts',
    state: {
      list: [],
      total: null,
    },
    reducers: {
      save(state, { payload: { data: list, total, page } }) {
        return { ...state, list, total, page };
      },
      saveUsers(state, { payload: { users }}) {
        return { ...state, users};
      },
      saveComments(state, { payload: { comments }}) {
        return { ...state, comments};
      },
    },
    effects: {
      *getUsers({ payload: {  page = 1 }}, { call, put }) {
        const { data } = yield call( postsService.getUsers);
        yield put({
          type: 'saveUsers',
          payload: {
            users: data,
          }
        })
      },
      *fetch({ payload: { page = 1 } }, { call, put }) {
        const { data, headers } = yield call( postsService.fetch, page );
        yield put({
          type: 'save',
          payload: {
            data,
            total: parseInt( headers['x-total-count'], 10 ),
            page: parseInt( page, 10 ),
          }
        })
      },
      *getComments({ payload: { id } }, { call, put }) {
        const { data } = yield call( postsService.getComments, id );
        yield put({
          type: 'saveComments',
          payload: {
            comments: data,
          }
        })
      },
    },
    subscriptions: {
      setup({ dispatch, history }) {
        return history.listen(({ pathname, query }) => {
          if (pathname === '/posts') {
            dispatch({ type: 'getUsers', payload: query });
            dispatch({ type: 'fetch', payload: query });
          }
        });
      },
    },
  };